package com.after.saas.common.config;

import feign.Feign;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import com.after.saas.common.interceptor.OkHttpLogInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by hcchen on 2021/7/18.
 */
@Data
@Slf4j
@Configuration
@EnableCaching
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@ConfigurationProperties(prefix = "rest")
public class RestTemplateConfig {

    /**
     * connect超时时间
     */
    private Integer connectTimeout;

    /**
     * read超时时间
     */
    private Integer readTimeout;

    /**
     * write超时时间
     */
    private Integer writeTimeout;

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    /**
     * 声明 RestTemplate
     */
    @Bean
    public RestTemplate httpRestTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    @Bean
    public OkHttpClient okHttpConfigClient() {
        log.info("connectTimeout {},readTimeout {}",connectTimeout,readTimeout);
        return new OkHttpClient().newBuilder()
                .connectionPool(new ConnectionPool())
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .addInterceptor(new OkHttpLogInterceptor())
                .build();
    }

    public ClientHttpRequestFactory httpRequestFactory() {
        return new OkHttp3ClientHttpRequestFactory(okHttpConfigClient());
    }

}
